package com.mehdiuz.backend.role.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.mehdiuz.backend.role.entity.*;
import com.mehdiuz.backend.role.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;


@Service
public class UserDetailsServiceImpl  implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private RoleMenuService roleMenuService;

    @Autowired
    private UserRoleService userRoleService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = userService.getBaseMapper().selectOne(new QueryWrapper<User>().eq("username", s));
        List<UserRole> userRoleList = userRoleService.getBaseMapper().selectList(new QueryWrapper<UserRole>().eq("user_id", user.getId()));
        List<Long> roleIds = userRoleList.stream().map(UserRole::getRoleId).collect(Collectors.toList());
        List<RoleMenu> roleMenuList = roleMenuService.getBaseMapper().selectList(new QueryWrapper<RoleMenu>().in("role_id", roleIds));
        List<Long> menuIds = roleMenuList.stream().map(RoleMenu::getMenuId).collect(Collectors.toList());
        List<Menu> menus = menuService.getBaseMapper().selectBatchIds(menuIds);
        List<String> perms = menus.stream().map(Menu::getPerms).filter(StringUtils::isNotBlank).collect(Collectors.toList());
        if(user==null){
            throw new UsernameNotFoundException("账号密码错误");
        }
        if(user.getStatus()==0){
            throw new RuntimeException("账号已停用");
        }
        return new CustomUser(user, perms);
    }
}
